const seq = require('./seq')
const { QueryTypes } = require('sequelize');
const moment = require('moment');
class dept {
//增加部门

  async updateDeptByID(dept) {
    const {id,name,code,managerID=0,introduce} = dept
    const currentTime = moment().format('YYYY-MM-DD HH:mm:ss');
    const sql = `update  department 
                set name=?,code=?,managerID=?,introduce=? ,updateTime=? where id=${id}` 
    const results = await seq.query(sql,
      {
        replacements: [name,code,managerID,introduce,currentTime],
        type: QueryTypes.UPDATE
      }
    )
    //更新

    return results
}

  async getdeptDetail(id) {
    const sql = `SELECT department.*, user.username
                FROM department LEFT JOIN  user 
                ON department.managerID = user.id
                where department.id=${id} and department.isDelete=0`
    const results = await seq.query(sql,
      {
        type: QueryTypes.SELECT
      }) 
    return results
  }

  async delDeptByid(id) {
    const sql = `update department set isDelete=1 where id=${id}`
    const results = await seq.query(sql,
      {
        type: QueryTypes.UPDATE
      }) 
    return results
  }

  async getAll() {
    const sql = `SELECT department.*, user.username
                FROM department LEFT JOIN  user 
                ON department.managerID = user.id
                where  department.isDelete=0`
    const results = await seq.query(sql,
      {
        type: QueryTypes.SELECT
      }) 
    return results
  }
  //校验部门编码是否重复
  async verifyCode(code) {
    const sql = `select * from department where code='${code}'`
    const results = await seq.query(sql,
      {
        type: QueryTypes.SELECT
      }) 
    return results
  }

  //校验部门名称是否重复
  async verifyName(name) {
    const sql = `select * from department where name='${name}'`
    const results = await seq.query(sql,
      {
        type: QueryTypes.SELECT
      }) 
    return results
  }

   //增加部门
  async addDept(dept) {
    const {pid,name,code,introduce} = dept
    
    const sql = `insert into department 
                set pid=?,name=?,code=?,introduce=?`
    const results = await seq.query(sql,
      {
        replacements: [pid,name,code,introduce],
        type: QueryTypes.INSERT
      }
    )

    return results
  }

  async updateuserIsdeptManager(id)
  {
    const sqlupduser = `update  user set isdeptmanager=1 where id=${id}` 
    await seq.query(sqlupduser,{type: QueryTypes.UPDATE})
  }
}


module.exports = new dept()